package com.user.basic.analyze.register;

import com.entity.analyze.RegisterType;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.lang.ref.Reference;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class QuarterRegisterAnalyzeServiceImpl extends RegisterAnalyzeServiceImpl {
    public QuarterRegisterAnalyzeServiceImpl(RegisterAnalyzeMapper registerAnalyzeMapper) {
        super(registerAnalyzeMapper);
    }

    @Override
    protected Map<String, Integer> transform(Reference<ConcurrentHashMap<String, List<Date>>> cache) {
        if (Objects.requireNonNull(cache.get()).size() >0){
            Map<String, Integer> countMap = new HashMap<>();
            cache.get().forEach((k, v) -> v.forEach(date -> countMap.compute((1900+date.getYear()+"-"
                            +Quarter.transform2Quarter(date.getMonth())),
                    RegisterAnalyzeServiceImpl::apply)
            ));
            return countMap;
        }
        return null;
    }

    @Override
    protected void save(Map<Object, Integer> transform) {
        save(transform, RegisterType.Quarter);
    }

    static class Quarter{
        static int transform2Quarter(int month){
            Assert.notNull(month,"month cannot be null...");
            if (month>=0 && month <=2){
                return 1;
            }else if (month >=3 && month <=5){
                return 2;
            }else if (month>=6 && month <=8){
                return 3;
            }else {
                return 4;
            }
        }
    }
}
